<?php
require_once 'function.inc.php';
require_once 'AopSdk.php';
require_once 'HttpRequst.php';
require_once 'config.php';
require_once 'UserInfo.php';
require_once 'PushMsg.php';
require_once 'config.php';
require_once 'MysqliDb.php';

$user_agent = $_SERVER['HTTP_USER_AGENT'];
$auth_code=  HttpRequest::getRequest ( "auth_code" );

if (isset($_COOKIE["user"])){
	$alipay_user_id=$_COOKIE["user"];
}
if(!stristr($user_agent,"AlipayClient") || !stristr($user_agent,"AlipayDefined")){
  header('Location:http://m.taobao.com'); // 不包含肯定不是支付宝访问的所以挑个网址吧
}
// alipays://platformapi/startapp?appId=20000042&publicBizType=LIFE_APP&publicId=2013110600000000

if (!isset($_COOKIE["user"]) && empty ( $auth_code )){ // 这里判断cokies不含有跳转到授权链接
  $ru= "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=".$config['app_id']."&scope=auth_userinfo&redirect_uri=".urlencode($config['url']);
  setcookie("user","");
  header('Location:'.$ru);
}
$db = new MysqliDb ($configDb);
if(!empty($alipay_user_id)){
	$results =$db
			->where ('alipay_user_id', $alipay_user_id) 
			->getOne('user');
	writeLog ( "db: " . var_export ( $results, true ) );
}

// 第二步 根据cookies 读取数据库

if(! empty ( $auth_code ) && empty($results)){
  $userinfo = new UserInfo ();
  $user_info_resp=$userinfo->getUserInfo ( $auth_code );
  writeLog("user_info_resp->".var_export ($user_info_resp, true ));
  $t=time();
  // 执行插入
  $data=Array(
    "alipay_user_id" => $user_info_resp->alipay_user_id,
    "user_id" => $user_info_resp->user_id,
    "avatar" => $user_info_resp->avatar,
    "nick_name" => !empty($user_info_resp->nick_name)?$user_info_resp->nick_name:'',
    "province" => !empty($user_info_resp->province)?$user_info_resp->province:'',
    "city" => !empty($user_info_resp->city)?$user_info_resp->city:'',
    "gender" => !empty($user_info_resp->gender)?$user_info_resp->gender:'',
    "is_certified" => !empty($user_info_resp->is_certified)?$user_info_resp->is_certified:'',
    "is_id_auth" => !empty($user_info_resp->is_id_auth)?$user_info_resp->is_id_auth:'',
    "is_mobile_auth" => !empty($user_info_resp->is_mobile_auth)?$user_info_resp->is_mobile_auth:'',
    "user_status" => !empty($user_info_resp->user_status)?$user_info_resp->user_status:'',
    "user_type_value" => !empty($user_info_resp->user_type_value)?$user_info_resp->user_type_value:'',
    "is_certify_grade_a" => !empty($user_info_resp->is_certify_grade_a)?$user_info_resp->is_certify_grade_a:'',
    "is_student_certified" => !empty($user_info_resp->is_student_certified)?$user_info_resp->is_student_certified:'',
    "create_time"=>$t
  );
  if(!empty($user_info_resp->alipay_user_id)){
  	$alipay_user_id=$user_info_resp->alipay_user_id;
    $count = $db
      ->where ('alipay_user_id', $alipay_user_id) 
      ->getValue ("user", "count(*)");
    writeLog("count->".$count);
    if($count==0){
      $id = $db->insert ('user', $data);
      if ($id){setcookie("user",$user_info_resp->alipay_user_id, time()+3600*24);}  
    }  
  	
  }
  
	  
}

header ( "Content-type: text/html; charset=utf-8" );
// 日志记录下受到的请求
writeLog ( "POST: " . var_export ( $_POST, true ) );
writeLog ( "GET: " . var_export ( $_GET, true ) );
?>
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="utf-8" />
  <title></title>
  <meta name="description" content="" />
  <meta name="keywords" content="" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <meta name="format-detection" content="telephone=no, email=no" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />
  <script>
    var docEl = document.documentElement;
    docEl.style.fontSize = 100 / 375 * docEl.clientWidth  + 'px';
    window.addEventListener('resize', function() {
      docEl.style.fontSize = 100 / 375 * docEl.clientWidth + 'px';
    });
  </script>
  <link rel="stylesheet" href="https://gw.alipayobjects.com/as/g/antui/antui/10.1.10/dpl/antui-all.css"/>
  <script src="https://unpkg.com/clipboard@2.0.0/dist/clipboard.min.js"></script>
  <script src="https://a.alipayobjects.com/amui/zepto/1.1.3/zepto.js"></script>
  <?php  
  if(!empty($alipay_user_id)){
  	echo "<script>";
  	echo 'var text="'.$Info["text"].' '.$Info["aliapy"].'";';
  	echo 'var user_id="'.$alipay_user_id.'";';
  	echo 'var url="'.$config['url'].'";';
  	echo 'var app_id="'.$config['app_id'].'";';
  	echo "</script>";
  }
  ?>
  </head>
<body ontouchstart="">
  <!--你的html页面代码-->
  <div class="header" style="background-color: #108ee9;">
    <div style="text-align:center;"> 
      <img src="./img/header4.png">
      <a id= "gz"style="width: 38.4px; height: 19.2px; border-radius: 19.2px; opacity: 0.6; position: absolute; right: 0px; top: 2px;"><span style="font-size: 10.56px; line-height: 19.2px; color: rgb(255, 255, 255); text-align: center;">规则</span></a>
    </div>
    <div style="text-align:center;"> <!-- class="am-textarea" -->
      <textarea rows="3" id="bar"></textarea>
      <div class="am-textarea-footer" style="text-align: center;">
          <button type="button" class="am-button loading copy">
            <div class="am-loading-indicator white" aria-hidden="true">
              <div class="am-loading-item"></div>
              <div class="am-loading-item"></div>
            </div>复制密令<div class="am-loading-indicator white" aria-hidden="true">
              <div class="am-loading-item"></div>
              <div class="am-loading-item"></div>
            </div>
          </button>
      </div>
    </div>
  </div>
  <?php
    /*echo $user_info_resp->alipay_user_id;
    echo "<br/>";
    echo $alipay_user_id;*/
  ?>
  <div class="am-list am-list-twoline">
      <div class="am-list-item">
          <div class="am-list-thumb"><img src="./img/logo.jpg" alt=""></div>
          <div class="am-list-content">
              <div class="am-list-title"><?php echo $config['name'];?></div>
              <div class="am-list-brief">服务由该生活号商户独家提供</div>
          </div>
          <a class="am-button dynamic" href="http://p.alipay.com/P/3VJv6QeE">关注</a>
      </div>
      
  </div>
  <div class="am-card">
    <div class="am-card-header" style="color: #171616;font-size: 14px;padding: 0 2px 6px;">其他活动</div>
      <div class="am-card-body">
        <!-- <a id ="cp" data-clipboard-text="<?php echo $Info['aliapy'];?>"><div class="am-card-item"> <div class="am-card-minfo"><div class="am-card-thumb"><img src="./img/alipay.png" /></div><div class="am-card-content"><div class="am-card-title">支付宝红包</div><div class="am-card-subtitle">每天领取一次</div></div></div><div class="am-card-footnote">进行中</div></div></a> -->

      	<?php
      		foreach ($Ad as $key => $value) {
			    echo '<a onclick="goto(\''.$value['url'].'\');"><div class="am-card-item"> <div class="am-card-minfo"><div class="am-card-thumb"><img src="'.$value['img'].'" /></div><div class="am-card-content"><div class="am-card-title">'.$value['title'].'</div><div class="am-card-subtitle">'.$value['des'].'</div></div></div><div class="am-card-footnote">'.$value['status'].'</div></div></a>';
			   }
      	?>
          
 			
      </div>
  </div>
<div class="am-dialog-mask"></div>
<!-- A11Y: 对话框隐藏时设置 aria-hidden="true"，显示时设置 aria-hidden="false" -->
<div class="am-dialog image" role="dialog" aria-hidden="false">
    <div class="am-dialog-wrap">
        <div class="am-dialog-header">
            <h3>活动介绍</h3>
        </div>
        <div class="am-dialog-body">
            <div style="text-align: left;">
              <?php echo $Info["help"];?>
            </div>
            <!-- <p class="am-dialog-brief">
              <?php echo $Info["help"];?>
          </p> -->
        </div>
        <a class="am-dialog-close"></a>
    </div>
</div>
<script type="text/javascript">
	function ready(callback) {
  // 如果jsbridge已经注入则直接调用
  if (window.AlipayJSBridge) {
    callback && callback();
  } else {
    // 如果没有注入则监听注入的事件
    document.addEventListener('AlipayJSBridgeReady', callback, false);
  }
}

/*    
  toast({
    content: '请稍等', // content  string  文字内容
    type:'success', // type string none / success / fail / exception
    duration: 3500, // duration int 显示时长，单位为毫秒。
  }, function(e){
    alert('toast消失回调');
  });
*/
function toast(config, callback){
  AlipayJSBridge.call('toast',config, callback);
}
function goto(url){
  AlipayJSBridge.call('pushWindow', {
    url: url,
    param: {
      readTitle: true,
      showOptionMenu: false
    }
  });
}


ready(function() {
  // 设置标题
  AlipayJSBridge.call('setTitle', {
    title: '618理想狂欢节',
  });
  AlipayJSBridge.call("setTitleColor", {
    color: parseInt('108ee9', 16),
    reset: false //(可选,默认为false)  是否重置title颜色为默认颜色。
  });
  AlipayJSBridge.call('setOptionMenu', {
    // 显示的时候是从后往前显示的
    menus: [/*{
      icontype: 'help',
      redDot: '-1', // -1表示不显示，0表示显示红点，1-99表示在红点上显示的数字
    },*/{
      title: '分享赚88¥',
      color : '#ff00ff00',
      redDot: '-1', // -1表示不显示，0表示显示红点，1-99表示在红点上显示的数字
    }],
    override: true //在需要设置多个option的情况下，是否保留默认的optionMenu
  });
  $('#gz').on('click', function(e){
    $(".am-dialog-mask,.am-dialog").addClass('show');
  })

  // 必须强制调用一把刷新界面
  AlipayJSBridge.call('showOptionMenu');
  document.addEventListener('optionMenu', function(e) {
    if (e.data.index==0){
      AlipayJSBridge.call("shareToChannel", {
        name: "ALPTimeLine", //"ALPContact" : 支付宝好友 "ALPTimeLine" : 支付宝我的生活 "ALPCommunity" : 支付宝生活圈
        param: {
          contentType: 'url',
          title: '恭喜发财,您有一个红包待领取！',
          content: '恭喜发财,您有一个红包待领取！',
          iconUrl: url+'/img/hb.jpg',
          imageUrl: url+'/img/hb.jpg',
          captureScreen: false, 
          url: url,
        }
        }, function(result) {
          if (result.shareResult){
            $.ajax({
              type: 'POST',
              url: '/trigger.php',
              data: { user_id: user_id },
              dataType: 'json',
              success: function(data){
                if (data.code!=="10000"){
                    toast({
                      content:data.msg,
                      type:"fail",
                      duration: 3500
                    });
                }else{
                  toast({
                      content:"恭喜您抽中"+data.prize_amount+"元红包",
                      type:'success',
                      duration: 3500
                    });
                }
                //window.location.href='alipays://platformapi/startapp?appId=20000042&publicBizType=LIFE_APP&publicId='+app_id;
                 
              },
              error: function(xhr, type){
                toast({
                  content:"Ajax error!",
                  type:"fail"
                });
              }
            });
          }else{
            toast({
              content:"分享失败",
              type:"fail"
            });
          }
          
        }
      );
    }
  }, false);
  $(".am-dialog-close").on('click', function(e){
    $(".am-dialog-mask,.am-dialog").removeClass('show');
  })
  var clipboard = new ClipboardJS('.copy', {
        text: function() {
            return text;
        }
    });
  clipboard.on('success', function(e) {
      $("#bar").val(text);
      toast({
        content:"复制成功,分享【微信好友】一起拆红包"
      });
  });
  clipboard.on('error', function(e) {
      toast({
        content:"复制失败"
      });
  })  
  setInterval(function(){
    $("#bar").val(text);
  },800); 
  
});
</script>
<script type="text/javascript" src="//js.users.51.la/19530877.js"></script>
</body>
</html>